package CGW.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("upload.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理上传的文件和表单的数据
        // 验证请求头的数据类型是否为 multipart/form-data
        System.out.println(req.getContentType());

        // 创建硬盘文件项的工厂类对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置工厂的缓存大小，便于文件读取（接收客户端发送文件字节数据）
        factory.setSizeThreshold(4096); // 4K

        // 创建文件上传的Servlet并解析req请求对象中的表单数据
        ServletFileUpload upload = new ServletFileUpload(factory);
        String note = null;
        String fileName = null;
        try {
            List<FileItem> items = upload.parseRequest(req);
            // 迭代表单的字段
            for (FileItem item : items) {
                // 判断item是否为表单字段（只有两种：表单字段和文件字段）
                if(item.isFormField()){
                    // 只有一个note表单字段
                    note = item.getString("utf-8");
                }else{
                    // 只一个文件字段 file1
                    // 保存文件
                    // 获取相对于应用上文的files实际路径
                    String filesPath = getServletContext().getRealPath("files");
                    fileName = item.getName(); // 原始的文件名
                    String mediaType = item.getContentType(); // 文件类型
                    item.write(new File(filesPath, fileName));

                }
            }
            req.getSession().setAttribute("msg", fileName+"上传成功");
            req.getSession().setAttribute("filepath", "/images/"+fileName);
            req.getSession().setAttribute("note", note);
            // 当前的请求是post请求， 不能跳转的【注意】
            resp.sendRedirect("/upload");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<div style='color:red'>");
            resp.getWriter().write(e.getLocalizedMessage());
            resp.getWriter().write("</div>");
        }

    }
}
